<template>
  <!-- 对话框 -->
  <el-dialog title="新增员工" :visible="showDialog" @close="close">
    <el-form ref="form" :model="form" :rules="rules">
      <el-form-item label="姓名" prop="username" :label-width="formLabelWidth">
        <el-input v-model="form.username" autocomplete="off" />
      </el-form-item>
      <el-form-item label="手机" prop="mobile" :label-width="formLabelWidth">
        <el-input v-model="form.mobile" autocomplete="off" />
      </el-form-item>
      <el-form-item
        label="入职时间"
        prop="timeOfEntry"
        :label-width="formLabelWidth"
      >
        <el-date-picker
          v-model="form.timeOfEntry"
          type="date"
          placeholder="选择日期"
          value-format="yyyy-MM-dd"
        />
      </el-form-item>
      <el-form-item
        label="聘用形式"
        prop="formOfEmployment"
        :label-width="formLabelWidth"
      >
        <el-select v-model="form.formOfEmployment" placeholder="请选择聘用形式">
          <el-option
            v-for="item in hireType"
            :key="item.id"
            :label="item.value"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item
        label="工号"
        prop="workNumber"
        :label-width="formLabelWidth"
      >
        <el-input v-model="form.workNumber" autocomplete="off" />
      </el-form-item>
      <el-form-item
        label="部门"
        prop="departmentName"
        :label-width="formLabelWidth"
      >
        <el-input
          v-model="form.departmentName"
          autocomplete="off"
          @focus="deptFocus"
          @blur="deptBlur"
        />
        <el-tree
          v-show="treeShow"
          v-loading="treeLoading"
          :data="treeData"
          :props="defaultProps"
          default-expand-all
          @node-click="handleNodeClick"
        />
      </el-form-item>

      <el-form-item
        label="转正时间"
        prop="correctionTime"
        :label-width="formLabelWidth"
      >
        <el-date-picker
          v-model="form.correctionTime"
          type="date"
          placeholder="选择日期"
          value-format="yyyy-MM-dd"
        />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
// 导入枚举库
import enumObj from '@/utils/constant/employees'
// 导入接口
import { getDepts } from '@/api/departments'
// 导入新增员工的接口
import { addEmp } from '@/api/employees'
// 导入工具
import { arrayToTree } from '@/utils'
export default {
  props: {
    showDialog: {
      type: Boolean,
      required: true
    }
  },
  data() {
    return {
      treeShow: false,
      // tree的加载动画
      treeLoading: false,
      defaultProps: {
        // 指定要显示的文字
        label: 'name'
      },
      treeData: [],

      // 表单里文字的宽度
      formLabelWidth: '80px',
      // 表单绑定的对象
      form: {
        // 为了避免bug，尽量要把这些属性都定义上，只不过默认值为空
        username: '',
        mobile: '',
        formOfEmployment: '',
        workNumber: '',
        departmentName: '',
        timeOfEntry: '',
        correctionTime: ''
      },
      // 声明一个数据保存枚举库里聘用形式数组
      hireType: enumObj.hireType,
      //   规则对象
      rules: {
        username: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: '请输入正确的手机号',
            trigger: 'blur'
          }
          // 作业：自定义校验规则：要查出所有的员工数据，再看输入的手机是否重复
          //   { validator: 函数, trigger: 'blur' },
        ],
        formOfEmployment: [
          { required: true, message: '请选择聘用形式', trigger: 'blur' }
        ],
        workNumber: [
          { required: true, message: '请输入工号', trigger: 'blur' }
        ],
        departmentName: [
          { required: true, message: '请选择部门', trigger: 'blur' }
        ],
        timeOfEntry: [
          { required: true, message: '请输入入职时间', trigger: 'blur' }
        ],
        correctionTime: [
          { required: true, message: '请输入转正时间', trigger: 'blur' }
        ]
      }
    }
  },

  methods: {
    // 保存的点击事件
    save() {
      // 整个表单验证
      this.$refs.form.validate(async(v) => {
        if (v) {
          // 验证通过，可以发请求
          const res = await addEmp(this.form)
          // 成功
          this.$message.success(res.message)

          // 关闭弹框
          this.$emit('update:showDialog', false)
          // 刷新父组件的数据
          // 先把父组件的页码设置为最后一页
          const pageInfo = this.$parent.pageInfo
          pageInfo.total++
          this.$parent.pageInfo.page = Math.ceil(pageInfo.total / pageInfo.size)
          // 调用数据刷新
          this.$parent.loadData()
        }
      })
    },
    // 关闭的事件
    close() {
      this.form = {
        username: '',
        mobile: '',
        formOfEmployment: '',
        workNumber: '',
        departmentName: '',
        timeOfEntry: '',
        correctionTime: ''
      }
      this.$refs.form.resetFields()
      this.$emit('update:showDialog', false)
    },
    // 部门获得焦点事件
    async deptFocus() {
      // 显示tree
      this.treeShow = true
      // 开启加载动画
      this.treeLoading = true

      // 要加载部门数据
      const res = await getDepts()
      // 再转成树形结构,赋值给跟tree绑定的数据
      this.treeData = arrayToTree(res.data.depts, '')
      // 隐藏加载动画
      this.treeLoading = false
    },
    // 失去焦点事件
    deptBlur(e) {
      // 获得失去焦点去的目标元素
      //   console.log(e.relatedTarget)

      // 如果没有 el-tree-node 这个类，代表去的是别的地方，绝对不是tree
      // 那么就隐藏，换句话说，如果失去焦点时去的是tree，就不隐藏了
      if (
        e.relatedTarget == null ||
        e.relatedTarget.className.indexOf('el-tree-node') == -1
      ) {
        this.treeShow = false
      }
    },

    // tree的节点被点击
    // 参数就是被点的这个节点绑定的数据
    handleNodeClick(data) {
      // 把被点的节点赋值给文本框
      this.form.departmentName = data.name
      // 把tree隐藏
      this.treeShow = false

      // 删掉校验结果
      this.$refs.form.clearValidate('departmentName')
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-tree-node__expand-icon {
  display: none;
}
</style>
